import sys

from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFrame, QVBoxLayout, QHBoxLayout


class MyClass(QWidget):
    def __init__(self):
        super().__init__()
        self.mycolor = QColor('#000')  # self.color.name()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('刘金玉编程')
        self.setGeometry(800, 370, 400, 300)

        btnRed = QPushButton('红')
        btnRed.setCheckable(True)  # 设置按钮组件可被选中开关状态
        btnRed.clicked[bool].connect(self.setColor)
        btnGreen = QPushButton('绿')
        btnGreen.setCheckable(True)  # 设置按钮组件可被选开关中状态
        btnGreen.clicked[bool].connect(self.setColor)
        btnBlue = QPushButton('蓝')
        btnBlue.setCheckable(True)  # 设置按钮组件可被选中开关状态
        btnBlue.clicked[bool].connect(self.setColor)

        vlo = QVBoxLayout()
        vlo.addWidget(btnRed)
        vlo.addWidget(btnGreen)
        vlo.addWidget(btnBlue)

        self.my_frame = QFrame(self)
        self.my_frame.setStyleSheet("QWidget{background-color:%s}" % self.mycolor.name())  # css样式语法
        hlo = QHBoxLayout(self)
        hlo.addLayout(vlo)
        hlo.addWidget(self.my_frame)

        self.show()

    def setColor(self, p):
        '''
        p : True / Flase
        b = self.sender().text()  : 红/绿/蓝
        '''
        b = self.sender()
        v = 255 if p else 0
        if b.text() == '红':
            self.mycolor.setRed(v)
        elif b.text() == '绿':
            self.mycolor.setGreen(v)
        elif b.text() == '蓝':
            self.mycolor.setBlue(v)

        print(self.mycolor.name())
        self.my_frame.setStyleSheet("QWidget{background-color:%s}" % self.mycolor.name())
        # Process finished with exit code -1073740791 (0xC0000409) 原因：初始化my_frame时需要 self.my_frame


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myf = MyClass()
    app.exec_()
